package com.xc.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.mapper.RoleMapper;
import com.xc.mapper.UserMapper;
import com.xc.model.Role;
import com.xc.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);

        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        List<Role> roles = roleMapper.getRolesByUid(user.getId());
        user.setRoles(roles);

        return user;
    }
}
